package pers.qianyu.month_202012.date_20201213;

import java.util.*;

/**
 * [leetcode 每日一题]
 * 217. 存在重复元素
 * https://leetcode-cn.com/problems/contains-duplicate/
 *
 * @author mizzle rain
 * @date 2020-12-13 15:30
 */
public class ContainsDuplicate {
    /**
     * 哈希表
     */
    public boolean containsDuplicate(int[] nums) {
        if (nums == null) {
            return false;
        }
        int len = nums.length;
        if (len < 2) {
            return false;
        }
        HashMap<Integer, Integer> dict = new HashMap<>();
        for (int num : nums) {
            dict.put(num, dict.getOrDefault(num, 0) + 1);
        }
        for (Integer value : dict.values()) {
            if (value > 1) {
                return true;
            }
        }
        return false;
    }

    /**
     * 排序
     */
    public boolean containsDuplicate2(int[] nums) {
        if (nums == null) {
            return false;
        }
        int len = nums.length;
        if (len < 2) {
            return false;
        }
        Arrays.sort(nums);
        for (int i = 0; i < nums.length; i++) {
            if (i != 0 && nums[i - 1] == nums[i]) {
                return true;
            }
        }
        return false;
    }
}
